<template>
  <card v-bind="cardOptions" @save="save">
    <y-form ref="$form" v-bind="formOptions" @change="formChangeHandler" @ready="formReadyHandler">
      <template slot="attributes">
        <el-row v-for="item in attributeOptions" :key="item.code">
          <el-col :span="1">{{item.label}}</el-col>
          <el-col :span="23">
            <el-checkbox v-model="option.checked" v-for="option in item.params" :key="option.id">{{option.name}}</el-checkbox>
          </el-col>
        </el-row>
      </template>
      <template slot="generateSkuBtn">
        <y-button label="生成SKU（将清理原有数据）" @click="generateSkuOptions"></y-button>
      </template>
    </y-form>
  </card>
</template>

<script>
export default {
  mounted() {
    var { keyValue, parentId } = this.$route.query;
    if (!!keyValue) {
      this.cardOptions.title = "商品 / 编辑";
      this.keyValue = keyValue;
    } else {
      this.cardOptions.title = "商品 / 新增";
    }
  },
  data() {
    return {
      keyValue: "",
      cardOptions: {
        title: "",
        btns: ["save", "back"],
      },
      formOptions: {
        items: [
          {
            title: "产品信息",
            fields: [
              { type: "input", field: "code", text: "编号" ,required: true },
              { type: "input", field: "name", text: "名称", required: true },
              { type: "input", field: "subName", text: "副名称", required: true },
              { type: "dataItem", field: "categroyId", text: "分类",action:'ProductCategroy'},
              // { type: "checkbox", field: "saleable", text: "上架",span:2 },
              { type: "checkbox-group", text: "选项", span:6,
                items:[
                  { field:"saleable",text:"上架" },
                  { field:"saleable2",text:"推荐" },
                  { field:"saleable3",text:"热销" },
                ] 
              },
              { type: "dataItem" ,field:"attributeSelect",text:"属性" , action:'Attribute',multiple: true,span:12 },
              { type:'slot',field:'attributes',span:24 },
              { type: "slot" ,field:"generateSkuBtn",span:24 },
              { type:"picture-group",field:'imgages',text:"相册", span:24 }
            ],
          },
          {
            title:"SKU列表",
            field:"details",
            height: "300px",
            edit: true,
            columns: [
              { type: "seq", width: 50 },
              { type:'tags', field: "options", title: "规格" },
              { field: "code", title: "编号" },
              { field: "images", title: "图片" },
              // { field: "specIndex", title: "规格" },
              { field: "price", title: "价格" },
              { field: "inventory", title: "库存" },
              { field: "warning", title: "库存预警" },
            ],
          },
          {
            title:"其他信息",
            fields:[
              { type: "rich-editor", field: "describe", text: "详情",span:24 },
            ]
          }
        ],
      },
      attributeOptions:[]
    };
  },
  methods: {
    initData(keyValue) {
      
    },
    async save() {
      var formData = this.$refs.$form.getFormData();
      formData.attributes = this.attributeOptions.map(a=>{ 
        return {
          productId:this.keyValue,
          attributeId:a.value,
          attributeDetailId:a.params.filter(s=>s.checked).map(s=>s.id).join(',')
        }
       })
      var { succeeded } = await $y.api.shop.product.save(formData);
      succeeded && $y.notifier.success('保存成功！')
    },
    /**
     * 生成SKU
     */
    async generateSkuOptions(){
      var { api } = this.$refs.$form.$refs.$details[0]
      var { code,name } = this.$refs.$form.getFormData()
      
      // 计算出有多少种组合：所有属性选中的参数条数相乘
      var totalCount = 1;
      // 找出所有选中的属性参数，已二维数组存放
      var attrOptions = []
      this.attributeOptions.forEach(attr=>{
        var checkedList = attr.params.filter(p=>p.checked);
        totalCount *= checkedList.length
        attrOptions.push(checkedList);
      })
      // await api.remove(api.getTableData().tableData)
      for (let i = 0; i < totalCount; i++) {
        var options = []
        for (let j = 0; j < attrOptions.length; j++) {
          var params = attrOptions[j];
          // 这里取余、循环取出属性中的选项
          var target = params[ i % params.length ]
          options.push(target.name)
        }
        var index = i + 1;
        await api.insertAt({
          seq:index,
          code:code + index,
          options:options,
          images:'',
          price:0,
          inventory:'',
          warning:'',
        },-1)
      } 
    },
    async formReadyHandler(){
      var that = this
      var { data } = await $y.api.shop.product.get(this.keyValue);
      // 属性格式化
      if(data.attributes){
        var formatAttrs = []
        data.attributes.forEach(a=>{
          var attr = that.$refs.$form.dataItemOptions.Attribute.find(s=>s.value == a.attributeId) || {}
          if(attr.params && a.attributeDetailId){
            var detailId = a.attributeDetailId.split(',')
            attr.params.forEach(d=>{
              d.checked = detailId.includes(d.id)
            })
          }
          formatAttrs.push(attr)
        })
        this.attributeOptions = formatAttrs;
        data.attributeSelect = formatAttrs.map(s=>s.value)
      }
      this.$refs.$form.setData(data);
    },
    /**
     * 数据修改事件
     */
    formChangeHandler({field,event}){
      if(field == 'attributeSelect')
        this.attributeOptions = this.$refs.$form.dataItemOptions.Attribute.filter(s=>event.includes(s.value));
    },

  },
};
</script>

<style lang="scss" scoped>
</style>